"""
基础解析器类
定义文档解析器的通用接口和方法
"""

import re
import logging
from abc import ABC, abstractmethod
from typing import Dict, List, Any

logger = logging.getLogger(__name__)


class BaseParser(ABC):
    """文档解析器基类"""
    
    def __init__(self):
        self.supported_extensions = []
        self._init_keywords()
    
    def _init_keywords(self):
        """初始化关键词映射"""
        self.section_keywords = {
            "功能需求": [
                "功能需求", "功能描述", "功能说明", "系统功能", "功能点", "功能模块",
                "用户管理", "角色权限", "权限管理", "资源访问", "审计日志", "系统集成", "安全防护",
                "登录功能", "注册功能", "管理功能", "控制功能", "查询功能", "统计功能",
                "订单管理", "商品管理", "支付管理", "库存管理", "用户中心",
                "功能", "模块", "子系统", "组件"
            ],
            "业务规则": ["业务规则", "业务逻辑", "处理规则", "业务流程", "规则", "约束", "限制"],
            "性能需求": ["性能需求", "性能指标", "并发要求", "响应时间", "性能", "并发", "吞吐量"],
            "安全需求": ["安全需求", "安全控制", "权限要求", "数据安全", "安全", "加密", "认证"],
            "接口需求": ["接口需求", "接口说明", "对外接口", "系统接口", "API", "接口"],
            "数据需求": ["数据需求", "数据规范", "数据结构", "数据流", "数据库", "数据"],
            "环境需求": ["环境需求", "部署要求", "系统环境", "运行环境", "环境", "部署"],
            "质量需求": ["质量需求", "质量标准", "可靠性", "可用性", "质量", "稳定性"]
        }
        
        self.flow_keywords = [
            "步骤", "流程", "过程", "操作", "处理",
            "if", "when", "then", "while", "for",
            "当", "如果", "否则", "循环", "遍历"
        ]
        
        self.constraint_keywords = [
            "必须", "应该", "需要", "不能", "禁止",
            "大于", "小于", "等于", "至少", "最多",
            "限制", "阈值", "范围", "时间", "次数"
        ]

    @abstractmethod
    def parse_content(self, content: bytes) -> str:
        """解析文档内容 - 子类必须实现"""
        pass

    def clean_text(self, text: str) -> str:
        """清理文本内容"""
        if not text:
            return ""
        
        original_length = len(text)
        logger.debug(f"开始清理文本，原始长度: {original_length} 字符")
        
        # 移除多余的空白字符，但保留换行结构
        text = re.sub(r'[ \t]+', ' ', text)
        text = re.sub(r'\n\s*\n\s*\n+', '\n\n', text)
        
        # 移除控制字符
        text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]', '', text)
        
        # 移除开头和结尾的空白
        text = text.strip()
        
        cleaned_length = len(text)
        logger.debug(f"文本清理完成，清理后长度: {cleaned_length} 字符")
        
        return text

    def extract_meaningful_content(self, content: str) -> str:
        """提取有意义的内容"""
        if not content or not content.strip():
            return ""
        
        lines = content.split('\n')
        meaningful_lines = []
        
        # 过滤规则
        skip_patterns = [
            r'^https?://',  # URL
            r'^ftp://',     # FTP地址
            r'^file://',    # 文件路径
            r'^\w+://',     # 其他协议
            r'^[A-Z]:\\',   # Windows路径
            r'^/',          # Unix路径
            r'^\s*$',       # 空行
            r'^[\s\-_=]{3,}$',  # 分隔线
            r'^\d+\s*$',    # 纯数字行
        ]
        
        for i, line in enumerate(lines):
            line = line.strip()
            
            if not line:
                continue
            
            # 检查是否匹配过滤规则
            should_skip = False
            for pattern in skip_patterns:
                if re.match(pattern, line, re.IGNORECASE):
                    should_skip = True
                    break
            
            if should_skip:
                continue
            
            # 跳过太短的行
            if len(line) < 3:
                continue
            
            # 跳过只包含特殊字符的行
            if re.match(r'^[^\w\u4e00-\u9fff]+$', line):
                continue
            
            meaningful_lines.append(line)
        
        result = '\n'.join(meaningful_lines)
        result = self.clean_text(result)
        
        logger.info(f"有意义内容提取完成，最终长度: {len(result)} 字符")
        
        return result

    def extract_sections(self, content: str) -> Dict[str, List[str]]:
        """从文本中提取各个部分的内容"""
        sections = {
            "功能需求": [],
            "业务规则": [],
            "性能需求": [],
            "安全需求": [],
            "接口需求": [],
            "数据需求": [],
            "环境需求": [],
            "质量需求": []
        }
        
        current_section = None
        lines = content.split('\n')
        
        # 检查是否有明确的部分标题
        has_explicit_sections = any(
            any(keyword in content for keyword in keywords)
            for keywords in self.section_keywords.values()
        )
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 检查是否是新的部分
            section_found = False
            for section, keywords in self.section_keywords.items():
                if any(keyword in line for keyword in keywords):
                    current_section = section
                    section_found = True
                    break
            
            # 智能判断部分类型
            if not section_found and not has_explicit_sections:
                if re.match(r'^\d+[\.\、]', line) or re.match(r'^[一二三四五六七八九十]+[\.\、]', line):
                    current_section = "功能需求"
                elif any(word in line for word in ["规则", "必须", "不能", "应该", "禁止", "限制"]):
                    current_section = "业务规则"
                elif any(word in line for word in ["性能", "响应时间", "并发", "吞吐量", "TPS", "QPS"]):
                    current_section = "性能需求"
                elif any(word in line for word in ["安全", "加密", "认证", "权限", "密码"]):
                    current_section = "安全需求"
                elif current_section is None:
                    current_section = "功能需求"
            
            # 将内容添加到当前部分
            if current_section and line:
                sections[current_section].append(line)
        
        # 如果功能需求为空，尝试从整个内容中提取
        if not sections["功能需求"]:
            for line in lines:
                line = line.strip()
                if line and (
                    re.match(r'^\d+[\.\、]', line) or
                    re.match(r'^[一二三四五六七八九十]+[\.\、]', line) or
                    any(word in line for word in ["功能", "管理", "系统", "用户", "操作", "处理", "支持"])
                ):
                    sections["功能需求"].append(line)
        
        return sections

    def extract_flows(self, content: str) -> List[str]:
        """提取业务流程"""
        flows = []
        lines = content.split('\n')
        current_flow = []
        
        for line in lines:
            line = line.strip()
            if not line:
                if current_flow:
                    flows.append('\n'.join(current_flow))
                    current_flow = []
                continue
            
            # 检查是否包含流程关键词
            if any(keyword in line.lower() for keyword in self.flow_keywords):
                if current_flow:
                    flows.append('\n'.join(current_flow))
                    current_flow = []
                current_flow.append(line)
            elif current_flow:
                current_flow.append(line)
        
        if current_flow:
            flows.append('\n'.join(current_flow))
        
        return flows

    def extract_constraints(self, content: str) -> List[str]:
        """提取约束条件"""
        constraints = []
        lines = content.split('\n')
        
        for line in lines:
            line = line.strip()
            if not line:
                continue
            
            # 检查是否包含约束关键词
            if any(keyword in line for keyword in self.constraint_keywords):
                constraints.append(line)
        
        return constraints

    def is_supported(self, file_extension: str) -> bool:
        """检查是否支持该文件扩展名"""
        return file_extension.lower() in self.supported_extensions
